package cn.book.servlet;

import cn.book.entity.BookQuery;
import cn.book.entity.Page;
import cn.book.service.BookQueryService;
import cn.book.service.impl.BookQueryServiceImpl;
import com.alibaba.fastjson.JSON;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.List;

public class BookQueryServlet extends HttpServlet {

    BookQueryService bookQueryService;
    @Override
    public void init() throws ServletException {
        bookQueryService = new BookQueryServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置请求编码格式
        request.setCharacterEncoding("UTF-8");
        //设置响应编码格式
        response.setContentType("text/html;charset=UTF-8");
        //创建PrintWriter输出流
        PrintWriter out = response.getWriter();
        String opr = request.getParameter("opr");
        if ("findAll".equals(opr)) {
            String bookName = request.getParameter("bookName");
            String bookType = request.getParameter("bookType");
            String bookAuthor = request.getParameter("bookAuthor");
            Integer pageIndex = Integer.valueOf(request.getParameter("pageIndex"));
            Integer totalCount = bookQueryService.getTotalBook(bookName,bookAuthor,bookType);
            Page page = new Page();
            page.setCurrPageNo(pageIndex);
            page.setPageSize(3);
            page.setTotalCount(totalCount);
            Integer from = (page.getCurrPageNo() - 1) * page.getPageSize();
            List<BookQuery> bookList = bookQueryService.getBookPage(bookName,bookAuthor,bookType,from,page.getPageSize());
            String data = JSON.toJSONString(bookList);
            out.print(data);
            //request.getSession().setAttribute("bookList", bookList);
        }

        out.flush();
        out.close();
    }
}
